//
//  TravelsViewController.m
//  hai游～
//
//  Created by jakf_17 on 15/5/21.
//  Copyright (c) 2015年 jakf_17. All rights reserved.
//

#import "TravelsViewController.h"
#import "travelsModel.h"
#import "CustomCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "AlterCustomCell.h"
#import "MJRefresh.h"
#import <AFNetworking/AFNetworking.h>
#import "TravelNotesDetailViewController.h"
#import "RecommendViewController.h"
@interface TravelsViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation TravelsViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.elementsArray = [NSMutableArray array];
        self.dic = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)dealloc
{
    [_array release];
    [_tableView release];
    [_elementsArray release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createMyTableView];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://api.breadtrip.com/v5/index/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSDictionary *dic = [NSDictionary dictionary];
        self.dic = responseObject;
//        self.next_start = [self.dic objectForKey:@"next_start"];
//        NSArray *array = [self.dic objectForKey:@"elements"];
//        self.elementsArray = [NSMutableArray arrayWithArray:array];
//        for (int i = 0; i< array.count; i++) {
//            
//            if (i > 2) {
//                
//                NSDictionary *subDic = array[i];
//                NSArray *subArray = [subDic objectForKey:@"data"];
//                NSDictionary *travelsDic = [subArray firstObject];
//                self.travels = [[travelsModel alloc] init];
//                [self.travels setValuesForKeysWithDictionary:travelsDic];
//                if ([subDic objectForKey:@"next_start"]) {
//                    self.travels.next_start = [subDic objectForKey:@"next_start"];
//                }
//                self.travels.type = [subDic objectForKey:@"type"];
//                
//                
//                [_array addObject:self.travels];
//                [self.travels release];
//            }
//        }
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}

- (void)createArrayWithDic
{
    self.next_start = [self.dic objectForKey:@"next_start"];
    NSArray *array = [self.dic objectForKey:@"elements"];
    self.elementsArray = [NSMutableArray arrayWithArray:array];
    for (int i = 0; i< array.count; i++) {
        
        if (i > 2) {
            
            NSDictionary *subDic = array[i];
            NSArray *subArray = [subDic objectForKey:@"data"];
            NSDictionary *travelsDic = [subArray firstObject];
            self.travels = [[travelsModel alloc] init];
            [self.travels setValuesForKeysWithDictionary:travelsDic];
            if ([subDic objectForKey:@"next_start"]) {
                self.travels.next_start = [subDic objectForKey:@"next_start"];
            }
            self.travels.type = [subDic objectForKey:@"type"];
            
            
            [_array addObject:self.travels];
            [self.travels release];
        }
    }
}

- (void)createMyTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
#pragma mark - 上下
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerAction:)];
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerAction:)];
    
    [_tableView release];
    
    
}

#pragma mark - 上拉刷新数据

- (void)headerAction:(id)sender
{    // 刷新
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
   NSString *path = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/"];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        self.array = [NSMutableArray array];
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
    // 拿到当前的下拉刷新控件,结束下拉控件
    [self.tableView.header endRefreshing];
}

#pragma mark - 上拉加载数据
- (void)footerAction:(id)sender
{
    NSString *path = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?next_start=%@",self.next_start];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [self createArrayWithDic];
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
    // 拿到当前的上拉加载控件,结束上拉控件
    [self.tableView.footer endRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UIScreen mainScreen].bounds.size.height / 3.1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellPool = @"cellPool";
    self.travels = _array[indexPath.row];
    if (self.travels.type.integerValue == 5) {
        AlterCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
        if (cell == nil) {
            cell = [[[AlterCustomCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"a"] autorelease];
        }
        [cell.alter_imageView sd_setImageWithURL:[NSURL URLWithString:self.travels.cover] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.alter_label.text = self.travels.cover_title;

        return cell;
    }
    if (self.travels.type.integerValue == 4) {
        CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellPool];
        if (cell == nil) {
            cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellPool] autorelease];
        }
        
        [cell.cover_image sd_setImageWithURL:[NSURL URLWithString:self.travels.cover_image_default] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.nameLabel.text = self.travels.name;
        NSDictionary *userDic = self.travels.user;
        [cell.userImage sd_setImageWithURL:[NSURL URLWithString:[userDic objectForKey:@"avatar_m"]] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.start_dayLabel.text =  [NSString stringWithFormat:@"%ld", self.travels.last_day.integerValue - 7];
        cell.day_countLabel.text =  [NSString stringWithFormat:@"%@", self.travels.day_count];
        cell.view_countLabel.text = [NSString stringWithFormat:@"%@", self.travels.view_count];
        cell.popular_placeLabel.text = self.travels.popular_place_str;
        cell.userNameLabel.text = [userDic objectForKey:@"name"];
        
        return cell;
    }
    else if (self.travels.type.integerValue == 7) {
        AlterCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
        if (cell == nil) {
            cell = [[[AlterCustomCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"a"] autorelease];
        }
        [cell.alter_imageView sd_setImageWithURL:[NSURL URLWithString:self.travels.cover] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.alter_label.text = self.travels.title;

        return cell;
        
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
    
}

#pragma mark 游记点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath.row = %ld", indexPath.row);
   
    self.travels = _array[indexPath.row];
    NSLog(@"webId%@", self.travels.notesId);
    
    if (self.travels.type.integerValue == 4) {
        TravelNotesDetailViewController *notesDetail = [[TravelNotesDetailViewController alloc] init];
        notesDetail.webId =  [NSString stringWithFormat:@"%@", self.travels.notesId ];
        [self.navigationController pushViewController:notesDetail animated:YES];
        [notesDetail release];
    } else {
        RecommendViewController *recommend = [[RecommendViewController alloc] init];
        recommend.url = self.travels.url;
        [self.navigationController pushViewController:recommend animated:YES];
        [recommend release];
    }

}

@end
